<?php
/**
 * app推送处理
 */
class PushController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;

	public function init() {

		$this->commonAction();	
	}

 
 /**
  * 手动推送消息
  */
  
 public function indexAction() {
		try {

		 $type= $this->_request->getParam ( 'type' );  
		 $type=$type=='student'?'student':'class';
		 $this->view->type = $type;

		 $sql="select value from setting where variable='push_test_version_".$type."'";
         $version = $this->_dbAdapter->fetchOne($sql);  
		 $this->view->version = $version;

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
     
//token列表
 public function tokenAction() {
		try {
 
			 $type= $this->_request->getParam ( 'type' );  
			 $type=$type=='student'?'student':'class';
			 $this->view->type = $type;
			 $table='';
			 
			 $where=' where 1=1  ';  
			//查询所有的
			if($type=='student'){
				$table.="student_token_v";
				$keywolrd =  $this->_request->getParam ( 'text' ); 
		        $this->view->keywolrd=$keywolrd;  
				$where.=' and username like "%'.$keywolrd.'%" or mobile like "%'.$keywolrd.'%" or realname  like "%'.$keywolrd.'%" ';
			  }else if($type=='class'){
				$table.="class_token_v";
			
			$groupid = ( int ) $this->_request->getParam ( 'groups' );
		    $schoolid = $this->_request->getParam ( 'school' ); 		
	        $classid  = $this->_request->getParam ( 'class' ); 
		    
		    $this->view->groups=$groupid; 
		    $this->view->school=$schoolid;  
		    $this->view->classid=$classid; 
				
			 if($schoolid){ 
				  $schoolarray=explode('_',$schoolid);  
				  $schoolid=$schoolarray['0'];
			  } 
			 if($groupid){
				  $where .=' and  groupid="'.$groupid.'" ';
				  $this->view->groupid= $groupid; 
				 }
			 if($schoolid){
			    $where .=' and  schoolid="'.$schoolid.'" '; 
				$this->view->schoolid= $schoolid; 
			    } 
			 if($classid){
			    $where .=' and  classid="'.$classid.'" ';
				  $this->view->classid= $classid; 
				 }  
			 
			  }
       
            $count = 50;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
    		$offset = ($curpage - 1) * $count; 
			 
			$sql='select SQL_CALC_FOUND_ROWS * from  '.$table.' '.$where.'    order by addtime desc';
			// echo $sql; exit;
			$this->view->result = $result =  $this->_dbAdapter->fetchAll($sql);
			
    		$param ['file'] = '/' . $this->controller . '/' . $this->action;
    		$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    		$param ['perpagenum'] = $count; // 每页显示的数目
    		$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    		$param ['curpage'] = $curpage; // 当前页码
			$this->view->allnum=$param ['totalnum'];

    		$page = new MyClass_Page ( $param );
    		$page->setvar (array('type' => $type));
			$this->view->page= $page->getNumPage (); 
			

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

 public function groupsAction() {
		try { 
         $sql="select * from  groups ";
	     $result = $this->_dbAdapter->fetchAll ($sql);
		 $str='';
		 for($i = 0; $i<count($result); $i++)
		{
	      $str .= "<option value='".$result[$i]['groupid']."'>".$result[$i]['groupname']."</option>";
		}
		  
	    echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//获取所有的校园列表
	  public function schoollistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		 
		  $sql="SELECT * FROM `groups` where groupid='".$p['id']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	 
/*			//连接运营库
			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		    $sql="select * from  school where groupid='".$p['id']."'";   
			$schoollist= $this->_dbAdapter->fetchAll ($sql);
	                 

			 
		 for($i = 0; $i<count($schoollist); $i++)
		{
		  $str .= "<option value='".$schoollist[$i]['schoolid'].'_'.$result['groupid']."'>".$schoollist[$i]['schoolname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	//获取所有的班级信息
	  public function classlistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost ();  
		  $array=explode('_',$p['id']);
		  
		  $sql="SELECT * FROM `groups` where groupid='".$array['1']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
	 
/*			//连接运营库
			$dbArray=array();
			$dbArray['host']=$result['dbhost'];
			$dbArray['username']=$result['dbusername'];
			$dbArray['password']=$this->authcode($result['dbpassword'], 'DECODE', 'mactop') ;
			$dbArray['dbname']=$result['dbname'];
			
			$dbAdapter = Zend_Db::factory ("PDO_MYSQL", $dbArray );
			Zend_Registry::set('dbAdapter', $dbAdapter);

			$dbAdapter=Zend_Registry::get('dbAdapter');
			$dbAdapter->query ( 'set names utf8');	
*/			 
		  $sql="select * from  class  where isdel=0 and schoolid='".$array['0']."' ";   
		  $classlist= $this->_dbAdapter->fetchAll ($sql);
	  
			 
		 for($i = 0; $i<count($classlist); $i++)
		{
		  $str .= "<option value='".$classlist[$i]['classid']."'>".$classlist[$i]['classname']."</option>";
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	 

   public function pushlistAction() {
		try { 

			$type = $this->_request->getParam ( 'type' );
			$type = $type=='student'?'student':'class';
			$this->view->type = $type;
			 
			$issend = $this->_request->getParam ( 'issend' );     
			$issend = $issend==1?1:0;
			$this->view->issend = $issend;

			$count = 50;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
    		$offset = ($curpage - 1) * $count; 
			 
			$table='push_'.$type.'_content';
				
			$sql='select SQL_CALC_FOUND_ROWS * from  push_'.$type.'_v where issent ='.$issend.' order by addtime desc limit '."$offset,$count";
			//echo $sql;
			$this->view->result = $result =  $this->_dbAdapter->fetchAll($sql);
			
    		$param ['file'] = '/' . $this->controller . '/' . $this->action;
    		$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    		$param ['perpagenum'] = $count; // 每页显示的数目
    		$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    		$param ['curpage'] = $curpage; // 当前页码
			$this->view->allnum=$param ['totalnum'];

    		$page = new MyClass_Page ( $param );
    		$page->setvar (array('type' => $type,'issend'=>$issend));
			$this->view->page= $page->getNumPage (); 
			
		 
        } catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}

/*
推送处理 ajax
*/
  public function sentAction() {
		try {
			
			$pushid =  intval($this->_request->getParam ( 'pushid' ));
			$type =   trim($this->_request->getParam ( 'type' ));
			$type = $type=='student'?'student':'class';
			 
			if(!$pushid)
			  throw new Exception ( -1 );
			  
			$sql='select * from  push_'.$type.'_v where issent =0 and pushid='.$pushid;
			$result=$this->_dbAdapter->fetchRow($sql);
			//print_r($result); exit;
			if(!$result){
				 throw new Exception ( -2 );
			}
			
		   	$res=$this->pushMessage($result['token'],$result['content'],$result['type'],$type,$result['contenttype'],$result['version']);  
		//	$this->log('@@@@@@ '.$result['token'].','.$result['content'].','.$result['type'].','.$type);

			if(!$res){
				 throw new Exception ( -3 );
			}
			$result = $this->_dbAdapter->update ('push_'.$type.'_content',array('issent'=>1,'senttime'=>time()),'issent =0 and pushid='.$pushid);
			
			throw new Exception ( $result);
			
        } catch ( Exception $e ) {
			echo $e->getMessage ();
			exit;
		}
	}

/**
 * 自动推送 
 * 跳过登陆验证
 */
  public function autoAction() {
		try {

			if(date('G')<=7 || date('G')>=21 ){
				exit;
			}

			 $type =array('student','class');
			//// 打开家长推送$type =array('class');
			$time=time();
			$i=0;
			
			foreach($type as $key => $value){
				
				$sql='select * from  push_'.$value.'_v where issent=0 and wantsenttime<='.$time.' order by addtime asc';
				//$this->log($sql);
				$result=$this->_dbAdapter->fetchAll($sql);
				if(!$result){
					 continue;
				}
				$token_contenttype_list=array();
				foreach($result as $key1=> $value1){
					//每token 每类型只发1次
					if(!isset($token_contenttype_list[$value1['token']]) || !in_array($value1['contenttype'],$token_contenttype_list[$value1['token']])){
						$token_contenttype_list[$value1['token']][]=$value1['contenttype'];
					}else{
						continue;
					}
						$res=$this->pushMessage($value1['token'],$value1['content'],$value1['type'],$value,$value1['contenttype'],$value1['version']);  
				
						if($res==1){
							//$sql='update push_'.$value.'_content set issent=1 where issent=0 and token="'.$value1['token'].'" and contenttype="'.$value1['contenttype'].'" and wantsenttime<='.$time;
							//echo $sql;   and token="'.$value1['token'].'"
							$result = $this->_dbAdapter->update ('push_'.$value.'_content',array('issent'=>1,'senttime'=>$time),'issent =0  and contenttype="'.$value1['contenttype'].'" and wantsenttime<='.$time);
							//print_r($result);exit;
							if(!$result)
								$this->log('error '.$value.' issent =0 and token="'.$value1['token'].'" and contenttype="'.$value1['contenttype'].'" and wantsenttime<='.$time);
								
							
						}else
							$this->log('false ' .var_export($res, true));	
							
						$i++;
					
				//if(mod($i,30)==0)
				if(($i%30)==0)
					sleep(2);
				}
				
				
			}

			//伊顿自动考勤处理
			/*
			$etonkidsDb=$this->getDbLink('etonkids');
			$sql='select uid,CheckTime from StudentAttendance_push_uid_v where CheckTime=';
			echo $sql;
			$result=$etonkidsDb->fetchRow($sql);
			
			print_r($result);
			*/
			
			//推送生日
			// 
			$nowdate=date('m-d');
			$push_birthday=$this->_dbAdapter->fetchOne('select `value` from `setting` where `variable`="push_birthday"');
			if($push_birthday!=$nowdate){
				$uidArr=$this->_dbAdapter->fetchCol('select uid from student where DATE_FORMAT(birthday, "%m-%d")=DATE_FORMAT(now(), "%m-%d");');
				if($uidArr){
					$content='云中校车祝你生日快乐。 Happy birthday to you!';
					$timenow=time();
					$wantsenttime=strtotime(date('Y-m-d 08:00'));
					$this->_dbAdapter->query('insert push_student_content (`uid`,`token`,`content`,`addtime`,`wantsenttime`,`contenttype`) select uid,token,"'.$content.'","'.$timenow.'","'.$wantsenttime.'","birthday" from push_student_token where  uid in ('.implode(',',$uidArr).')');
					$push_birthday=$this->_dbAdapter->update('setting',array('value'=>$nowdate),'`variable`="push_birthday"');
				}
			}
			
			$this->log('over '.$i);	
			exit;
        } catch ( Exception $e ) {
			$this->log($e->getMessage ());
			//echo $e->getMessage ();
			exit;
		}
	} 

 /**
  * 采用 百度云推送
  */
  public function opAction() {
		try {
		  
		   //获取推送的人和内容 
		   
		   $token =   $this->_request->getParam ( 'token' ); 
		   $version =   $this->_request->getParam ( 'version' ); 
		   $content =   $this->_request->getParam ( 'content' );   
		   $version_type =   $this->_request->getParam ( 'version_type' );
		   
           $type =  $this->_request->getParam ( 'type' );   
		   $type = $type=='student'?'student':'class';

		   if( empty($token) ){			     
				 throw new Exception ( '请填写token！' ); 			   
			}
			   
		  if( empty($content) ){			     
				 throw new Exception ( '请填写要发送的内容！' ); 			   
			}	   
		  
		   if( empty($version_type) ){			     
				 throw new Exception ( '请选择终端类别！' ); 			   
			 }

			$content=strip_tags($content);
			$content=str_replace(chr(13) ,'',$content);
			$content=str_replace(chr(10) ,'',$content);

		       
		 
		   //发送推送通知  
		   $res=$this->pushMessage($token,$content,$version_type,$type,'hand',$version);  

	      if($res==1){  
		  		$sql='select uid from push_'.$type.'_token where token="'.$token .'" and type="'.$version_type.'"';
				$uid=$this->_dbAdapter->fetchOne($sql);
				
				if(!$uid){
					$uid=0;
					
					$info=array(
						'token'=>$token,
						'type'=>$version_type,
						'uid'=>$uid,
						'addtime'=>time()
					);
					$result = $this->_dbAdapter->insert ('push_'.$type.'_token',$info);  
				}
				
				$data=array(
					'uid'=>$uid,
					'token'=>$token,
					'content'=>$content,
					'contenttype'=>'hand',
					'addtime'=>time(),
                    'issent'=>'1',
					'senttime'=>time()
				);
			   $result = $this->_dbAdapter->insert ('push_'.$type.'_content',$data);  
				 
				 throw new Exception ( '发送成功!' ); 		 
				
			}else{ 
				   throw new Exception ( $e->getMessage () ); 
			} 
		
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
 /**
   给教师 推送 
    API Key：E0ll59HSdfBl1mfzICTVyfeQ
	Secret Key：OnRCU9YNjgUDO8M4VDgteIamOiQK11d7 
	
   给家长推送
    API Key：O0WbIjGH5GG0QK3fYITeImI0   
	Secret Key：hUK356VWPDisZKSzpxQsLZltj1DPqMmI
*
 */
 	
	protected function pushMessage ($token,$content,$type,$producttype='student',$message_type,$version=0){
		
		$producttype=='class'?'class':'student';

		if($producttype=='student'){ 
		
		 //$sql="select value from setting where variable='push_test_version_student'";
         //$studentversion = $this->_dbAdapter->fetchOne($sql);;   
		
			//if($version!=$studentversion){
				//正式版
				//$apiKey = 'qFaOUDHv7xFOz3yT1dgsPAtT';
				//$secretKey = 'p4ArL7yV7aN0AshwhTuXj20jsf7d6FE7';
				//$sethostvalue='1';
			//}else{
				//测试版
				$apiKey = 'qFaOUDHv7xFOz3yT1dgsPAtT';
				$secretKey = 'p4ArL7yV7aN0AshwhTuXj20jsf7d6FE7';
				 $sethostvalue='0';
			//}
		}elseif($producttype=='class'){

         //$sql="select value from setting where variable='push_test_version_teacher'";
         //$teacherversion = $this->_dbAdapter->fetchOne($sql);;   
			
			//if($version!=$teacherversion){
				//教师助手正式版 仅有 ios
			  // $apiKey    = 'Gh2BNx5mpL9FqO3WOjuf3SQn';
			  // $secretKey = '34GgLTozyEejW4kCrBmhrRYkN7B9ZC7v';  
			  // $sethostvalue='1';
			//}else{
			   $apiKey    = 'Gh2BNx5mpL9FqO3WOjuf3SQn';
			   $secretKey = '34GgLTozyEejW4kCrBmhrRYkN7B9ZC7v';  
 			 $sethostvalue='0';

			//} 
		}
		
	    $res=-1; 
	  	$content=strip_tags($content);
	  	$content=str_replace(chr(13) ,'',$content);
	  	$content=str_replace(chr(10) ,'',$content); 

		if($type=='android'){ 
		   	$res=$this->pushMessage_android($token,$apiKey ,$secretKey,$content,$message_type);  
		}elseif($type=='ios'){
			$res=$this->pushMessage_ios($token,$apiKey,$secretKey,$content,$message_type,$sethostvalue); 
		}
	
		return $res;
	}
	 
	 
	  //推送ios设备消息
	protected function pushMessage_ios ($user_id, $apiKey, $secretKey ,$content,$message_type=0,$sethostvalue)
	{

		$this->log("$user_id, $apiKey, $secretKey ,$content,$message_type,$sethostvalue");
	    // echo $user_id.'aaa'.$apiKey.'nnn'.$secretKey.'-'.$message_type;  exit;
		$channel = new PushSdk_Channel ( $apiKey, $secretKey ) ;
		//注意百度push服务对ios dev版与ios release版采用不同的域名.
		//如果是dev版请修改push服务器域名"https://channel.iospush.api.duapp.com", release版则使用默认域名,无须修改。修改域名使用setHost接口
		// if($sethostvalue!='1'){
		 //开发版本(测试版)
		  //$channel->setHost("https://channel.iospush.api.duapp.com");
		 //}//else{ 
		  //正式版本
		  //$channel->setHost("http://channel.api.duapp.com");
		 //}
		$push_type = 1; //推送单播消息
		$optional[PushSdk_Channel::USER_ID] = $user_id; //如果推送单播消息，需要指定user
	
		//指定发到ios设备
		$optional[PushSdk_Channel::DEVICE_TYPE] = 4;
		//指定消息类型为通知 ios消息必须指定消息类型为1
		$optional[PushSdk_Channel::MESSAGE_TYPE] = 1;
		//测试版是1，正式版是2
	    $optional[PushSdk_Channel::DEPLOY_STATUS] = 2;
		
		//通知类型的内容必须按指定内容发送，示例如下：
		$message = '{ 
			"aps":{
				"alert":"'.$content.'",
				"sound":"default",
				"badge":1
			},
			"key" :"'.$message_type.'"
		}'; 
		
		$message_key = time().rand(1,10000);
		//echo "$push_type, $message, $message_key, $user_id";exit;
		$ret = $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
			$this->log('ret:' . var_export($ret,true));
		if ( false === $ret )
		{ 
		//	$this->error_output ( 'WRONG, ' . __FUNCTION__ . ' ERROR!!!!!' ) ;
		//    $this->error_output ( 'ERROR NUMBER: ' . $channel->errno ( ) ) ;
		//    $this-> error_output ( 'ERROR MESSAGE: ' . $channel->errmsg ( ) ) ;
		//    $this->error_output ( 'REQUEST ID: ' . $channel->getRequestId ( ) );
			$this->log('ERROR NUMBER: ' . $channel->errno ( ) );
			$this->log( 'ERROR MESSAGE: ' . $channel->errmsg ( ) );
			$this->log( 'REQUEST ID: ' . $channel->getRequestId ( ));						

		   
			return $channel->errno ( );
			 
		}else{    
		
		   return 1;
		 
		}
	}
 

	//推送android设备消息
	protected function pushMessage_android ($user_id, $apiKey, $secretKey ,$content,$message_type=0)
	{      

		$channel = new PushSdk_Channel( $apiKey, $secretKey ) ;
		//推送消息到某个user，设置push_type = 1; 
		//推送消息到一个tag中的全部user，设置push_type = 2;
		//推送消息到该app中的全部user，设置push_type = 3;
		$push_type = 1; //推送单播消息
		$optional[PushSdk_Channel::USER_ID] = $user_id; //如果推送单播消息，需要指定user
		//optional[Channel::TAG_NAME] = "xxxx";  //如果推送tag消息，需要指定tag_name
	
		//指定发到android设备
		$optional[PushSdk_Channel::DEVICE_TYPE] = 3;
		//指定消息类型为通知
		$optional[PushSdk_Channel::MESSAGE_TYPE] = 1;
		//通知类型的内容必须按指定内容发送，示例如下：
		
		/*$content1=explode('。',$content);
		if(is_array($content1)){
			$title=$content1[0].'。';
			$content=$content1[1];
		}else{
			$title='云中校车';
			$content=$content1;
		}
		*/
		$title='云中校车';
		
		$message = '{ 
				"title": "'.$title.'",
				"description": "'.$content.'",
				"open_type":2,
				"custom_content": {
				"key":"'.$message_type.'" 
				}
			}';
				//"notification_basic_style":7,
				//"open_type":1,
				//"url":"/"
		
		//$message_key = "msg_key";
		$message_key = rand(1,100);

		$ret = $channel->pushMessage ( $push_type, $message, $message_key, $optional ) ;
	  //   $ret=true;
		if ( false === $ret )
		{
			
			//$this->error_output ( 'WRONG, ' . __FUNCTION__ . ' ERROR!!!!!' ) ;
		    //$this->error_output ( 'ERROR NUMBER: ' . $channel->errno ( ) ) ;
		    //$this-> error_output ( 'ERROR MESSAGE: ' . $channel->errmsg ( ) ) ;
		    //$this->error_output ( 'REQUEST ID: ' . $channel->getRequestId ( ) );
			$this->log('ERROR NUMBER: ' . $channel->errno ( ) );
			$this->log( 'ERROR MESSAGE: ' . $channel->errmsg ( ) );
			$this->log( 'REQUEST ID: ' . $channel->getRequestId ( ));						
			return $channel->errno ( );
		}
		else
		{
			return 1;
		}
	}
 
	protected function error_output ( $str ) 
	{
		echo "\033[1;40;31m" . $str ."\033[0m" . "\n";
	}

	protected function right_output ( $str ) 
	{
		echo "\033[1;40;32m" . $str ."\033[0m" . "\n";
	}
 
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method "' . $method . '" called' );
	}

}

